<template>
  <div>
    <a-tree ref="tress"
            checkable
            :tree-data="treeData"
            :selectable="false"
            :expanded-keys="expandedKeys"
            checkStrictly
            v-model="checkedKeys"
            :loadData="lazyTree"
            @expand="onExpand"
            @check="onCheck">
      <template slot="title"
                slot-scope="record">
        {{ record.dataRef.name }}
      </template>
    </a-tree>
  </div>
</template>

<script>
import PropTypes from '@zh/common-utils/prop-types'
import _isEmpty from 'lodash/isEmpty'
import _cloneDeep from 'lodash/cloneDeep'
import { findSubPersion } from './api.js'
export default {
  name: 'TreeData',
  props: {
    treeData: PropTypes.array.def([]),
    type: PropTypes.string.def(''),
    value: PropTypes.array.def([]),
    service: PropTypes.string.def('')
  },
  data () {
    return {
      checkedKeys: {
        checked: []
      },
      expandedKeys: [],
      keys: []
    }
  },
  computed: {
    selectables () {
      return !!(this.type == 'role' || this.type == 'unit')
    }
  },
  watch: {
    value: {
      handler (value) {
        this.keys = value || []
        this.checkedKeys = this.setCheckedKeys(value || [])
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    this.expandedKeys = ['-1', '-2', '-3']
  },
  methods: {
    // 设置 checkedKeys 的值
    setCheckedKeys (data = []) {
      const checked = []
      const halfChecked = []
      // 判断父级节点下的所有非机构节点是否全部被选中，全部选中则勾选，否则处于半选状态
      const process = (list = []) => {
        for (const node of list) {
          if (!node.children) {
            continue
          }
          if (node.key.includes('_') || this.type !== 'user') {
            const childList = this.type === 'user' ? node.children.filter(item => !item.key.includes('_')) : node?.children
            let count = 0
            for (const child of childList) {
              if (data.includes(child.key)) {
                count++
              }
            }
            if (count > 0 && count === childList.length) {
              checked.push(node.key)
            } else if (count > 0) {
              halfChecked.push(node.key)
            }
          }
          if (node.children.length > 0) {
            process(node.children)
          }
        }
      }
      process(this.treeData)
      return {
        checked: [...data, ...checked],
        halfChecked
      }
    },
    getLazyTree (node) {
      return new Promise((resolve) => {
        findSubPersion(this.service, { id: node.id, type: node.type }).then((response) => {
          resolve(response)
        })
      })
    },
    lazyTree (treeNode) {
      if (treeNode.dataRef.key != '-1' && treeNode.dataRef.key != '-2' && treeNode.dataRef.key != '-3') {
        treeNode.dataRef.checkable = true
      }
      return new Promise((resolve, reject) => {
        // 当展开根节点，不请求
        if (!treeNode.dataRef.key.startsWith('-')) {
          this.getLazyTree(treeNode.dataRef).then(res => {
            res.map(item => {
              if (item.type == 21) {
                item.checkable = false
              }
            })
            if (res && res.length == 0) {
              // 设置成叶子节点
              treeNode.dataRef.isLeaf = true
            }
            treeNode.dataRef.children = res
            this.checkedKeys = this.setCheckedKeys(this.checkedKeys.checked)
            resolve()
          })
        } else {
          resolve()
        }
      })
    },
    onCheck (value, { checked, checkedNodes, node, event }) {
      const childList = this.getChildKeys(node.dataRef)
      const checkedList = this.checkedKeys.checked
      if (checked) {
        let handleKeys = [] // 根据不同类型处理已选中的key集合
        checkedList.push(...childList)
        if (this.type === 'user') {
          handleKeys = checkedList.filter(key => {
            return !key.includes('_')
          })
        } else {
          handleKeys = [...value.checked]
        }
        this.keys = [...new Set([...this.keys, ...handleKeys])]
        this.$emit('input', this.keys)
      } else {
        // 当父级节点取消勾选，则所有的的子节点也取消勾选
        if (childList.length > 0) {
          for (let i = checkedList.length - 1; i >= 0; i--) {
            if (childList.includes(checkedList[i])) {
              checkedList.splice(i, 1)
            }
          }
        }
        let list = [...checkedList]
        if (this.type === 'user') {
          list = list.filter(key => !key.includes('_'))
        }
        this.$emit('input', list)
        this.$emit('cancel', {
          type: this.type,
          item: node.dataRef
        })
      }
    },
    onExpand (value, { expanded, node }) {
      this.expandedKeys = value
      if (expanded) {
        this.checkedKeys = this.setCheckedKeys(this.checkedKeys.checked)
      }
    },
    getChildKeys (parentNode) {
      const list = this.type === 'user'
        ? parentNode.children.filter(item => { return !item.key.includes('_') })
        : parentNode.children
      return list.map(item => item.key)
    }
  }
}
</script>

<style>
</style>